//
//  MWShopSearchController.m
//  XiRan-iOS
//
//  Created by liuyiming on 2019/12/8.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWShopSearchController.h"
#import "MWShopSearchResultController.h"

#import "MWSearchCell.h"
#import "MWSearchHeaderView.h"
#import "MWSearchFlowLayout.h"

@interface MWShopSearchController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIImageView *searchIV;
@property (nonatomic, strong) UITextField *searchTF;
@property (nonatomic, strong) UIButton *searchBtn;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) MWShopSearchResultController *resultController;

@property (nonatomic, strong) NSMutableArray *hotSearchArray;

@end

@implementation MWShopSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"search" defaultValue:@"搜索"];

    [self setupPageSubviews];
    [self layoutPageSubviews];
    [self loadHotSearch];
}

- (void)searchAction:(UIButton *)sender {
    [self.view endEditing:YES];
    if ([MWConfigManager manager].isNetError) {
        self.resultController.view.hidden = YES;
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        self.collectionView.hidden = YES;
        return;
    }
    self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
    self.collectionView.hidden = NO;
    self.isSearch = YES;
    [_resultController searchWithKeyword:_searchTF.text];
}

- (void)textFieldDidChanged:(UITextField*)textField {
    if (textField.text.length == 0) {
        _searchBtn.enabled = NO;
    
    } else {
        _searchBtn.enabled = YES;
    }
}

#pragma mark - 热门搜索类型
- (void)loadHotSearch {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    [[MWNetworkManager manager] POST:kHotSearchUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSArray *tempArray = [MWGoods mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            [self.hotSearchArray addObjectsFromArray:tempArray];
            [self.collectionView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        collectionView.hidden = YES;
    } else if (!self.hotSearchArray.count) {
        if (self.isFirst) {
            
        } else {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            collectionView.hidden = YES;
        }
        
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        collectionView.hidden = NO;
    }
    return self.hotSearchArray.count;
}

- (void)refresh {
    [super refresh];
    if ([MWConfigManager manager].isNetError) {
        self.resultController.view.hidden = YES;
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        self.collectionView.hidden = YES;
        return;
    }
    self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
    self.collectionView.hidden = NO;
    if (self.searchTF.text && self.searchTF.text.length) {
        [self searchAction:self.searchBtn];
    } else {
        [self loadHotSearch];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableview = nil;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader]){
        MWSearchHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MWSearchHeaderView" forIndexPath:indexPath];
        headerView.title = [[MWConfigManager manager] objectForKey:@"hot_search" defaultValue:@"热门搜索"];
        reusableview = headerView;
    }

    return reusableview;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MWSearchCell *searchCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MWSearchCell" forIndexPath:indexPath];
    MWGoods *goods =  self.hotSearchArray[indexPath.row];
    searchCell.title = goods.store_name;
    return searchCell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    MWSearchCell *searchCell = (MWSearchCell *)cell;
    MWGoods *goods =  self.hotSearchArray[indexPath.row];
    searchCell.title = goods.store_name;
};

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    MWGoods *goods =  self.hotSearchArray[indexPath.row];
    return [MWSearchCell getSizeWithText:goods.store_name];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MWGoods *goods =  self.hotSearchArray[indexPath.row];
    _searchTF.text = goods.store_name;
    [self textFieldDidChanged:_searchTF];
    [_resultController searchWithKeyword:_searchTF.text];
}


- (NSMutableArray *)hotSearchArray {
    if (!_hotSearchArray) {
        _hotSearchArray = [[NSMutableArray alloc] init];
    }
    return _hotSearchArray;
}

- (void)setupPageSubviews {
    _searchView = [[UIView alloc] init];
    _searchView.backgroundColor = MWHexColor(@"#F6F7FB");
    _searchView.layer.cornerRadius = 10;
    _searchView.layer.masksToBounds = YES;
    [self.view addSubview:_searchView];
    
    _searchIV = [[UIImageView alloc] init];
    _searchIV.image = [UIImage imageNamed:@"ic_search_white"];
    [_searchView addSubview:_searchIV];
    
    _searchTF = [[UITextField alloc] init];
    _searchTF.font = MWFont(12);
    _searchTF.textColor = MWHexColor(@"#333333");
    if ([[MWConfigManager manager].productType isEqualToString:@"0"]) {
        _searchTF.placeholder = [[MWConfigManager manager] objectForKey:@"input_want_wood" defaultValue:@"请输入你想要查找的木头"];
    } else {
        _searchTF.placeholder = [[MWConfigManager manager] objectForKey:@"input_want_cailiao" defaultValue:@"请输入你想要查找的材料"];
    }
    [_searchTF addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [_searchView addSubview:_searchTF];
    
    _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _searchBtn.enabled = NO;
    _searchBtn.titleLabel.font = MWFont(14);
    [_searchBtn setTitleColor:MWHexColor(@"#333333") forState:UIControlStateNormal];
    [_searchBtn setTitleColor:MWHexColor(@"#FD9F2B") forState:UIControlStateHighlighted];
    [_searchBtn setTitleColor:MWHexColor(@"#999999") forState:UIControlStateDisabled];
    [_searchBtn setTitle:[[MWConfigManager manager] objectForKey:@"search" defaultValue:@"搜索"] forState:UIControlStateNormal];
    [_searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_searchBtn];
    
    MWSearchFlowLayout *layout = [[MWSearchFlowLayout alloc] init];
    layout.headerReferenceSize = CGSizeMake(kScreenWidth, 30);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.listItemSpace = 10;
    layout.sectionInset = UIEdgeInsetsMake(20, 16, 0, 16);
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[MWSearchCell class] forCellWithReuseIdentifier:@"MWSearchCell"];
    [_collectionView registerClass:[MWSearchHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MWSearchHeaderView"];
    [self.view addSubview:_collectionView];
    
    _resultController = [[MWShopSearchResultController alloc] init];
    _resultController.view.hidden = YES;
    [self.view addSubview:_resultController.view];
    [self addChildViewController:_resultController];
}

- (void)layoutPageSubviews {
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(28);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.searchBtn.mas_left).offset(-16);
        make.height.equalTo(@40);
    }];
    
    [_searchIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchView).offset(16);
        make.centerY.equalTo(self.searchView);
        make.width.height.equalTo(@20);
    }];
    
    [_searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchIV.mas_right).offset(15);
        make.right.equalTo(self.searchView).offset(-15);
        make.centerY.equalTo(self.searchView);
        make.height.equalTo(@30);
    }];
    
    [_searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.centerY.equalTo(self.searchView);
        make.height.equalTo(@30);
        NSDictionary *btAtt = @{NSFontAttributeName : MWFont(14)};
        CGSize btSize = [[[MWConfigManager manager] objectForKey:@"search" defaultValue:@"搜索"] sizeWithAttributes:btAtt];
        CGFloat with = btSize.width + 5;
        make.width.equalTo(@(with));
    }];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom).offset(40);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-16);
    }];
    
    [_resultController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom).offset(5);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}




@end
